package com.fengjing.launcher.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RecoverySystem;
import android.os.SystemProperties;
import android.support.annotation.Nullable;

import com.haijing.highglass.HmdCtrl;

import java.io.File;
import java.io.IOException;

/**
 * Created by wangjianqiang on 2017/9/25.
 */

public class CheckService extends Service {
    private static final long MAX_TIME = 2000 * 24 * 3600 * 1000;//10 * 60 * 3600;//48 * 3600 * 1000;
    private static final int TIME_UNIT = 60 * 1000;
    private static final int UNLOCK_LCD_TIME_UNIT = 1000;
    private static final int UNLOCK_LCD = 2;
    private static final int CHECK_TIME = 1;
    private static final String CHECK_TIME_ACTION = "com.ariplane.checkservice.checktime";
    private static final String OVER_TIME = "com.ariplane.checkservice.overtime";
    private static final String UPDATE_ACTION = "com.ariplane.checkservice.update";
    private static final String UNLOCK_HANDLE_ACTION = "com.ariplane.checkservice.unlock_handle";
    private boolean verifying;
    private MyReceiver myReceiver;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler.sendEmptyMessage(CHECK_TIME);
        mHandler.sendEmptyMessage(UNLOCK_LCD);
        myReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(UPDATE_ACTION);
        filter.addAction(UNLOCK_HANDLE_ACTION);
        registerReceiver(myReceiver, filter);
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(myReceiver);
        super.onDestroy();
    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CHECK_TIME:
                    boolean hasInit = getSharedPreferences("record", MODE_PRIVATE).getBoolean("hasInit", false);
                    long initTime = getSharedPreferences("record", MODE_PRIVATE).getLong("initTime", 0);
                    boolean hasLocked = getSharedPreferences("record", MODE_PRIVATE).getBoolean("hasLocked", false);
                    if (hasLocked) {
                        sendBroadcast(new Intent("com.ariplane.checkservice.overtime"));
                    } else if (hasInit && System.currentTimeMillis() - initTime > MAX_TIME) {
                        SharedPreferences.Editor editor = getSharedPreferences("record", MODE_PRIVATE).edit();
                        editor.putBoolean("hasLocked", true);
                        editor.commit();
                        sendBroadcast(new Intent("com.ariplane.checkservice.overtime"));
                        try {
                            File file = new File(Environment.getExternalStorageDirectory()+"/"+"lock.txt");
                            if(!file.exists()){
                                file.createNewFile();
                            }
                        }catch (Exception e){

                        }
                    }else{
                        sendEmptyMessageDelayed(CHECK_TIME,TIME_UNIT);
                    }
                    break;
                case UNLOCK_LCD:
                    HmdCtrl.unlock_lcd();
                    sendEmptyMessageDelayed(UNLOCK_LCD, UNLOCK_LCD_TIME_UNIT);
                    break;
            }
        }
    };

    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(UPDATE_ACTION)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (verifying) {
                            return;
                        }
                        verifying = true;
                        try {
                            final File recoveryfile = new File("/data/media/0/update.zip");
                            RecoverySystem.verifyPackage(recoveryfile, new RecoverySystem.ProgressListener() {
                                @Override
                                public void onProgress(int progress) {

                                    if (progress == 100) {
                                        try {
                                            SystemProperties.set("media.rkffplayer.ready", "false");
                                            SystemProperties.set("media.rkffplayer.mode", "common");
                                            int repeatCount = 0;
                                            while (true) {
                                                if (repeatCount > 30) {
                                                    verifying = false;
                                                    return;
                                                }
                                                boolean ready = SystemProperties.getBoolean("media.rkffplayer.ready", false);
                                                if (!ready) {
                                                    Thread.sleep(100);
                                                } else {
                                                    break;
                                                }
                                                repeatCount++;
                                            }
                                            SystemProperties.set("persist.sys.upgrade.lastVersion", getSystemVersion());
                                            RecoverySystem.installPackage(CheckService.this, recoveryfile);
                                        } catch (IOException e) {
                                            verifying = false;
                                            e.printStackTrace();
                                        } catch (InterruptedException e) {
                                            verifying = false;
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }, null);
                        } catch (Exception e) {
                        }
                    }
                }).start();
            }
            if (action.equals(UNLOCK_HANDLE_ACTION)) {
                SharedPreferences sharedPreferences = getSharedPreferences("record", MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean("hasInit", false);
                editor.putLong("initTime", 0);
                editor.putBoolean("hasLocked",false);
                editor.commit();
                try {
                    File file = new File(Environment.getExternalStorageDirectory()+"/"+"lock.txt");
                    if(file.exists()){
                        file.delete();
                    }
                }catch (Exception e){

                }
            }
        }
    }
    public static String getSystemVersion() {
        String version = SystemProperties.get("ro.product.version");
        if (version == null || version.length() == 0) {
            version = "1.0.0";
        }

        return version;
    }
}
